"""
@Project:p8-master
@File:comment.py
@Author:柴奇峰
@Date:19:36
"""
from flask import Blueprint,jsonify,json,g
from flask_restful import Api,marshal,Resource,reqparse
from model.courses import Comments
from model.user_model import User
from model import db
from model.courses import Course,UserCourse
from common.uilts.jwt_auth import check_token
from model.model_filter import comments_fields,user_fields
from common.uilts.login_jwt import login_required

comment_bp = Blueprint('comment_bp',__name__,url_prefix='/comment')
api = Api(comment_bp)



class Commentall(Resource):
    def get(self):
        parse = reqparse.RequestParser()
        parse = parse.add_argument("course_id")
        args = parse.parse_args()
        course_id = args.get("course_id")
        comment = Comments.query.filter_by(course=course_id).all()
        comment_data = marshal(comment, comments_fields)
        comment_data_ser = json.loads(json.dumps(comment_data))
        for i in comment_data_ser:
            user = User.query.filter_by(uid=i["user"]).first()
            user_info = marshal(user, user_fields)
            i["user_info"] = user_info

            parent = Comments.query.filter_by(parent_id=i["id"]).all()
            parent_comment = marshal(parent, comments_fields)
            parent_comment_ser = json.loads(json.dumps(parent_comment))
            for j in parent_comment_ser:
                user = User.query.filter_by(uid=j["user"]).first()
                user_info = marshal(user, user_fields)
                j["user_info"] = user_info

            i["parent_list"] = parent_comment_ser

        return jsonify(message="ok！", code=200, data=comment_data_ser)


class Commentadd(Resource):
    def post(self):
        parse = reqparse.RequestParser()
        parse = parse.add_argument("content")
        parse = parse.add_argument("cid")
        parse = parse.add_argument("reply")
        args = parse.parse_args()

        content = args.get("content")
        cid = args.get("cid")
        reply = args.get("reply")
        print("发表评论", content, cid, reply)

        user_id = g.user_id

        if cid:
            comment = Comments(user=user_id, course=cid, content=content)
        else:
            comment = Comments(user=user_id, parent=reply, content=content)

            comment_one = Comments.query.filter_by(id=reply).first()
            if not comment_one:
                return jsonify(message="该评论不存在！", code=401)

            # 更新回复量
            Comments.query.filter_by(id=reply).update({"reply_count": comment_one.reply_count + 1})
            db.session.commit()

        db.session.add(comment)
        db.session.commit()
        return jsonify(message="发表成功！", code=200, )


class Commentliking(Resource):
    # @login_required
    # def post(self):
    #     parse = reqparse.RequestParser()
    #     parse.add_argument('com_id')
    #     parse.add_argument('receive_id')
    #     args = parse.parse_args()
    #     cid = args.get('com_id')
    #     user_id = args.get('receive_id')
    #     print('文章id%s，用户id%s'%(cid,user_id))
    #     liking = CommentLiking.query.filter_by(user_id = user_id,comment_id=cid).first()
    #     print('liking',liking)
    #     if liking.is_deleted == 0:
    #         CommentLiking.query.filter_by(comment_id = cid).update({'is_deleted':1})
    #         Comments.query.filter_by(id=cid).update({'reply_count':Comments.reply_count-1})
    #         db.session.commit()
    #
    #         return jsonify(msg='取消点赞成功',code=200,)
    #     else:
    #         comment=CommentLiking(user_id=user_id,comment_id=cid)
    #         CommentLiking.query.filter_by(comment_id=cid).update({'is_deleted': 0})
    #         Comments.query.filter_by(id=cid).update({'reply_count':Comments.reply_count+1})
    #         db.session.add(comment)
    #         db.session.commit()
    #
    #         return jsonify(msg='点赞成功',code=200,)
    def post(self):
        parse = reqparse.RequestParser()
        parse.add_argument('com_id')
        parse.add_argument('receive_id')
        args = parse.parse_args()
        cid = args.get('com_id')
        user_id = args.get('receive_id')
        comment = Comments.query.filter_by(user=user_id,id=cid).first()
        if comment.is_favorite == 0:
            Comments.query.filter_by(id=cid).update({'is_favorite':1})
            Comments.query.filter_by(id=cid).update({'reply_count':comment.reply_count+1})
            db.session.commit()
            comm=Comments.query.filter_by(id=cid).first()
            data = {
                'is_favorite':comm.is_favorite
            }

            return jsonify(msg='点赞成功', code=200,data=data)
        else:
            Comments.query.filter_by(id=cid).update({'is_favorite': 0})
            Comments.query.filter_by(id=cid).update({'reply_count': comment.reply_count - 1})
            db.session.commit()
            comm = Comments.query.filter_by(id=cid).first()
            data = {
                'is_favorite': comm.is_favorite
            }
            return jsonify(msg='取消点赞成功',code=201,data=data)


# 用户关注
class Userattention(Resource):
    def post(self):
        parse = reqparse.RequestParser()
        parse.add_argument('id')    #课程id
        parse.add_argument('token')
        args = parse.parse_args()
        id = args.get('id')
        token = args.get('token')
        print('登录用户关注的课程',id,token)

        try:
            payload = check_token(token[3:])
        except Exception as e:
            print('解码错误',e)
            return jsonify(message='请先登录',code=401)
        uid = payload.get('id')
        print('token解码的用户信息',payload)
        print('uid',uid)

        user_course = UserCourse.query.filter_by(uid=uid,cid=id).first()
        if user_course:
            if user_course.is_delete == 0:
                UserCourse.query.filter_by(uid=uid,cid=id).update({'is_delete':1})
                course = Course.query.filter_by(id=id).first()
                Course.query.filter_by(id=id).update({'attention':course.attention+1})

                db.session.commit()
                return jsonify(code=200,message='重新关注成功')
            UserCourse.query.filter_by(uid=uid,cid=id).update({'is_delete': 0})
            course = Course.query.filter_by(id=id).first()
            Course.query.filter_by(id=id).update({'attention':course.attention-1})
            db.session.commit()
            return jsonify(code=201, message='取消关注成功')

        users_course = UserCourse(uid=uid,cid=id,is_delete=1)
        db.session.add(users_course)
        db.session.commit()
        return jsonify(code=200,msg='首次关注成功')







api.add_resource(Commentall,'/get_comment')
api.add_resource(Commentadd,'/add_comment')
api.add_resource(Commentliking,'/favorite_comment')
api.add_resource(Userattention,'/attention')